<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #resourceGroupSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择分组名称" @search="groupHandleView" />
      </template>
      <template #unitSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择单位" @search="unitHandleView" />
      </template>
      <template #manufactureFactorySlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择生产厂家" @search="manufactureFactoryHandleView" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="资源管理使用明细" key="busResourceAdministrationDetail" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="busResourceAdministrationDetail"
          :loading="busResourceAdministrationDetailTable.loading"
          :columns="busResourceAdministrationDetailTable.columns"
          :dataSource="busResourceAdministrationDetailTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        />
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 单位 -->
  <unitSelectModel @register="unitRegModal" @getSelectResult="unithandleSuccess" v-bind="getBindValue"></unitSelectModel>
  <!-- 分组 -->
  <groupingSelectModel @register="groupingRegModal" @getSelectResult="groupinghandleSuccess" v-bind="getBindValue"></groupingSelectModel>
  <!-- 供应商 -->
  <supplierSelectModel @register="supplierRegModal" @getSelectResult="supplierHandleSuccess" v-bind="getBindValue"></supplierSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, busResourceAdministrationDetailColumns } from '../BusResourceAdministration.data';
import { saveOrUpdate, busResourceAdministrationDetailList, saveItemOrUpdate } from '../BusResourceAdministration.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import unitSelectModel from '/@/views/components/unitSelectModel.vue';
import groupingSelectModel from '/@/views/components/resourceGroupingSelectModel.vue';
import supplierSelectModel from '/@/views/components/supplierSelectModel.vue';
import { localStorage } from '/@/utils/store/locaStore'

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref<boolean>()
const formDisabled = ref(false);
const refKeys = ref(['busResourceAdministrationDetail']);
const activeKey = ref('busResourceAdministrationDetail');
const busResourceAdministrationDetail = ref();
const tableRefs = { busResourceAdministrationDetail };
const busResourceAdministrationDetailTable = reactive({
  loading: false,
  dataSource: [],
  columns: busResourceAdministrationDetailColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(busResourceAdministrationDetailList, { id: data?.record?.id }, busResourceAdministrationDetailTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);

//设置标题
const title = computed(() => ( unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'busResourceAdministrationDetail';
  busResourceAdministrationDetailTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    busResourceAdministrationDetailList: allValues.tablesValue[0].tableData,
  };
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    values.departmentName = localStorage.get('departmentId')
    localStorage.remove('departmentId')
    // //提交表单
    // await saveOrUpdate(values, isUpdate.value);
    // //关闭弹窗
    // closeModal();
    // //刷新列表
    // emit('success');
    // console.log(busPurchaseReceiveItem);
    
    // let list = busPurchaseReceiveItem.value!.getTableData();
    //提交表单
    // const resp = await saveOrUpdate(values, isUpdate.value);
    await saveOrUpdate(values, isUpdate.value);
    // if (resp) {
    //   for (let i in list) {
    //     list[i].purchaseReceiveId = !unref(isUpdate) ? resp : values.id;
    //     list[i].id = !unref(isUpdate) ? null : list[i].id;
        // await saveItemOrUpdate(values.busResourceAdministrationDetailList[0], !isUpdate.value);
    //     //关闭弹窗
        closeModal();
    //     //刷新列表
        emit('success');
    //   }
    // }
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
const getBindValue = Object.assign({}, '');

const [unitRegModal, { openModal: openUnitModal }] = useModal();
const [groupingRegModal, { openModal: openGroupingModal }] = useModal();
const [supplierRegModal, { openModal: openSupplierModal }] = useModal();

//打开选择单位
function unitHandleView(props) {
  openUnitModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择分组
function groupHandleView(props) {
  openGroupingModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开生产厂家
function manufactureFactoryHandleView() {
  openSupplierModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//单位选择回写
function unithandleSuccess(val, values) {
  setFieldsValue({
    unit: val[0].label,
    unitId: val[0].value,
  });
}
//分组选择回写
function groupinghandleSuccess(val, values) {
  setFieldsValue({
    resourceGroup: val[0].label,
    resourceGroupId: val[0].value,
  });
}
//生产厂家选择回写
function supplierHandleSuccess(val, values) {
  setFieldsValue({
    manufacturerId: val[0].label,
    resourceGroupId: val[0].value,
  });
}

</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>